package allen.ui.log.example;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import allen.log.Log;
import allen.log.LogFactory;
import allen.log.LogLevel;
import allen.ui.log.LogListener;

/**
 * This is an exmaple to show how to use ui log.
 * */
public class LogExampleFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	private static int msgCount = 0;
	/**
	 * Show how to get the Log.
	 * */
	private static Log classLog = LogFactory.getLog(LogExampleFrame.class);
	private static Log nameLog = LogFactory.getLog("ui example");
	private JButton logButton = new JButton("Log");
	private JButton classMsgButton = new JButton("Msg");

	private void initSelf() {
		this.setPreferredSize(new Dimension(400, 300));
		this.setMinimumSize(new Dimension(400, 300));
		this.setTitle("UI logger example");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	private void addText() {
		StringBuilder sb = new StringBuilder();
		sb.append("This an example program for UI logger.\n");
		sb.append("\n");
		sb.append("Click Msg Button to generate the log event.\n");
		sb.append("Click Log Button to turn on or off the log windows.\n");
		JTextArea jta = new JTextArea();
		jta.setText(sb.toString());
		jta.setEditable(false);
		this.add(jta, BorderLayout.CENTER);
	}

	private void addButton() {
		classMsgButton.setToolTipText("Click me to generate the log event.");
		logButton.setToolTipText("Click me to turn on or off the log windows.");
		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		buttonPanel.add(classMsgButton);
		buttonPanel.add(logButton);
		this.add(buttonPanel, BorderLayout.SOUTH);
	}

	private void initComponent() {
		addText();
		addButton();
	}

	private void addListeners() {
		// Show how to add UI log windows to the JComponent.
		logButton.addActionListener(new LogListener());

		classMsgButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				LogLevel[] values = LogLevel.values();
				Random r = new Random();
				LogLevel level = values[r.nextInt(values.length)];
				// Make a log.
				if (r.nextBoolean()) {
					classLog.log(level, "log message #" + msgCount++);
				} else {
					nameLog.log(level, "log message #" + msgCount++);
				}
			}
		});
	}

	public void initAndShow() {
		initComponent();
		addListeners();
		initSelf();
	}
}
